package com.nf.practice.utils;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description:
 * @author: Thinkpad
 * @date: 2020/7/7 17:36
 */
public class JsonPathUtil {

    private static final Logger logger = LoggerFactory.getLogger(com.nf.practice.utils.JsonPathUtil.class);

    /**
     * 判断 JSON 字符串中是否有该字段值
     *
     * @param jsonPath
     * @return
     */
    public static <T> T read(String jsonPath, DocumentContext parse, Class<T> clazz, T defaultValue, T ExceptionValue) {

        T result = null;
        try {
            result = parse.read(jsonPath, clazz);
        } catch (PathNotFoundException e) {
            logger.info("返回json字符串中,JsonPath-{}-无返回值", jsonPath);
            return defaultValue;
        } catch (Exception e){
            return ExceptionValue;
        }
        return result;
    }

    /**
     * @param parseStr 带解析报文
     * @param indicator 加工指标log
     * @return
     */
    public static DocumentContext parse(String parseStr, String indicator){
        DocumentContext documentContext = null;
        try{
            documentContext = JsonPath.parse(parseStr);
        } catch (Exception e){
            logger.info("{}报文解析异常: 联系系统管理员,待解析报文为{}", indicator, StringUtils.isEmpty(parseStr) ? null : parseStr);
        }
        return documentContext;
    }

    /**
     * 取节点
     *
     * @param parse
     * @param jsonPath         节点路径
     * @param defaultValue 默认值
     */
    public static String getValue(DocumentContext parse, String jsonPath, String defaultValue, String ExceptionValue) {
        String result = read(jsonPath, parse, String.class, defaultValue, ExceptionValue);
        if (StringUtils.isNotEmpty(result)) {
            return result;
        }
        return defaultValue;
    }

    //jsonPath解析配置
    private static Configuration conf = Configuration.builder().jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider()).build();

    /**
     * @param parseStr 带解析报文
     * @param indicator 加工指标log
     * @return
     */
    public static DocumentContext parseUseConfig(String parseStr, String indicator){
        DocumentContext documentContext = null;
        try{
            documentContext = JsonPath.using(conf).parse(parseStr);
        } catch (Exception e){
            logger.info("{}报文解析异常: 联系系统管理员,待解析报文为{}", indicator, StringUtils.isEmpty(parseStr) ? null : parseStr);
        }
        return documentContext;
    }
}
